package process

import (
	"context"
	"errors"
	"quipus/internal/database/model"
	"quipus/internal/utils"
	apb "quipus/proto/gen/assist"
)

func (p *Process) GetModelProvider(ctx context.Context, modelId int32) (*model.LlmProvider, *model.LlmModel, error) {
	model, err := p.Gds.Handler.GetLLMModel(ctx, modelId)
	if err != nil || model == nil {
		return nil, nil, err
	}

	provider, err := p.Gds.Handler.GetLLMProvider(ctx, model.ProviderID)
	if err != nil || provider == nil {
		return nil, nil, err
	}
	return provider, model, nil
}

func (p *Process) GetAssistant(ctx context.Context, userId int32) (*model.LlmAssistant, error) {
	favorAssistants, err := p.Gds.Handler.ListUserFavorAssistant(ctx, userId)
	if err != nil {
		return nil, err
	}

	if len(favorAssistants) < 1 {
		return nil, errors.New("no favor assistant found")
	}

	favorAssistant := favorAssistants[0]

	assistor, err := p.Gds.Handler.GetLLMAssistant(ctx, favorAssistant.AssistantID)
	return assistor, err
}

func (p *Process) GetGeneralAssistant(ctx context.Context) (*model.LlmAssistant, error) {
	user, err := p.Gds.Handler.GetUser(ctx, &apb.FindUser{Username: "general"})
	if err != nil {
		return nil, err
	}
	return p.Gds.Handler.GetLLMAssistant(ctx, user.ID)
}

func (p *Process) GetAssistantAllInfo(ctx context.Context, assistantUrn string) (*model.LlmAssistant, *model.LlmModel, *model.LlmProvider, error) {
	id, e := utils.ExtractIDFromUrn(utils.AssistantUrnPrefix, assistantUrn)
	if e != nil {
		return nil, nil, nil, e
	}

	assistant, err := p.Gds.Handler.GetLLMAssistant(ctx, id)
	if err != nil {
		return nil, nil, nil, err
	}

	provider, model, err := p.GetModelProvider(ctx, assistant.ModelID)
	if err != nil {
		return nil, nil, nil, err
	}

	return assistant, model, provider, nil
}
